package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.UserLike;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FriendService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.sql.Struct;
import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    // 查询今日佳人
    public ResponseEntity findTodayBest() {
        //  1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.调用rpc查询缘分值最高用户
        RecommendUser recommendUser = recommendUserService.findTodayBest(toUserId);
        // 空值处理
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setScore(RandomUtil.randomDouble(90, 99));
            recommendUser.setUserId(1L);
            recommendUser.setToUserId(toUserId);
        }
        // 3.封装vo
        // 3-1查询userInfo
        UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());
        // 3-2 创建vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());

        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    // 查询推荐用户列表
    public ResponseEntity findRecommendUserVoByPage(Integer pageNum, Integer pageSize) {
        // 1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.分页查询推荐用户
        PageBeanVo pageBeanVo = recommendUserService.findRecommedUserByPage(toUserId, pageNum, pageSize);
        // 3.封装vo
        // 3-1 声明voList
        List<RecommendUserVo> voList = new ArrayList<>();
        // 3-2 获取recommendUserList
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 3-3 被遍历recommendUserList
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 查询推荐用户的（佳人）userInfo
                UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfo); // 用户信息
                vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值
                // 添加到集合
                voList.add(vo);
            }
        }
        // 4.将voList设置到分页对象
        pageBeanVo.setItems(voList);

        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 佳人详情
    public ResponseEntity findPersonalInfo(Long jiarenId) {
        // 1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.调用rpc查询二人的缘分值
        RecommendUser recommendUser = recommendUserService.findByJiarenIdAndToUserId(jiarenId, toUserId);
        // 空值处理 附近的人要用、我的动态也要用
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setScore(RandomUtil.randomDouble(60, 90));
        }
        // 3.查询userInfo
        UserInfo userInfo = userInfoService.findByUserId(jiarenId);
        // 4.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue()); // 设置缘分值

        // 5.返回vo
        return ResponseEntity.ok(vo);
    }

    @DubboReference
    private VisitorService visitorService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 查询历史访客
    public ResponseEntity visitors() {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.获取redis中上次登录时间 
        String userLoginTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        // 3.判断
        List<Visitor> visitorList;
        if (StrUtil.isNotEmpty(userLoginTime)) { // 有
            visitorList = visitorService.findVisitorHead5(userId, Long.valueOf(userLoginTime));
        } else { // 没有
            visitorList = visitorService.findVisitorHead5(userId, System.currentTimeMillis());
        }
        // 4.封装vo
        // 4-1 声明voList
        List<VisitorVo> voList = new ArrayList<>();
        // 4-2 遍历 visitorList
        if (CollectionUtil.isNotEmpty(visitorList)) {
            for (Visitor visitor : visitorList) {
                // 查询userInfo
                UserInfo userInfo = userInfoService.findByUserId(visitor.getVisitorUserId());
                // 创建vo
                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfo); // 用户信息
                vo.setFateValue(visitor.getScore().longValue()); // 你俩的缘分值
                // 添加到集合
                voList.add(vo);
            }
        }
        // 5.记录本次登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        // 6.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private UserLocationService userLocationService;

    // 调用manager
    public void saveLocation(Double latitude, Double longitude, String addrStr) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc保存
        userLocationService.saveLocation(latitude, longitude, addrStr, userId);
    }

    // 搜附近
    public ResponseEntity searchNearUser(String gender, Long distance) {
        //  1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        List<Long> nearUserIdList = userLocationService.searchNearUser(userId, distance);
        // 3.遍历
        List<NearUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(nearUserIdList)) {
            for (Long nearUserId : nearUserIdList) {
                // 排除自己
                if (userId == nearUserId) {
                    continue;
                }
                // 查询userInfo
                UserInfo userInfo = userInfoService.findByUserId(nearUserId);

                // 排除性别
                if (!StrUtil.equals(userInfo.getGender(), gender)) {
                    continue;
                }

                // 封装vo
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                // 添加集合
                voList.add(vo);
            }
        }

        // 4.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private QuestionService questionService;

    // 查看对方的陌生人问题
    public ResponseEntity strangerQuestions(Long jiarenId) {
        // 1.查询佳人的陌生人问题
        Question question = questionService.findByUserId(jiarenId);
        // 2.默认值处理
        if (question == null) {
            question = new Question();
        }
        // 3.返回问题
        return ResponseEntity.ok(question.getStrangerQuestion());
    }

    //查询推荐用户卡片
    public ResponseEntity findRecommendCards() {
        //获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        //调用rpc查询
        List<RecommendUser> recommendUserList = recommendUserService.findRecommendUser(toUserId);
        //判空，遍历
        List<RecommendUserInfoVo> voList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser user : recommendUserList) {
                RecommendUserInfoVo vo = new RecommendUserInfoVo();
                UserInfo userInfo = userInfoService.findByUserId(user.getUserId());
                vo.setUserInfo(userInfo);
                voList.add(vo);
            }
        }
        //返回查询到的用户信息集合
        return ResponseEntity.ok(voList);
    }

    //左滑不喜欢
    public void unLove(String userId) {
        //根据用户id删除推荐用户中的信息
        recommendUserService.remove(Long.valueOf(userId));
        if (recommendUserService.findRecommendUser(Long.valueOf(userId)) == null) {
            findRecommendCards();
        }
    }

    @DubboReference
    private FriendService friendService;

    //右滑喜欢
    public void love(String userId) {
        //获取用户toUserId
        Long toUserId = UserHolder.get().getId();
        //判断对方时候喜欢你，如果喜欢你就加对方为好友，如果不喜欢就将对方的信息保存到user_like表中
        UserLike userLike = recommendUserService.alreadyLove(Long.valueOf(userId),toUserId);
        if (userLike == null) {

            //将喜欢的用户添加到喜欢表中
            //根据当前用户id查询
            userLike = new UserLike();
            userLike.setCreated(System.currentTimeMillis());
            userLike.setUserId(Long.valueOf(toUserId));
            userLike.setLikeUserId(Long.valueOf(userId));
            recommendUserService.loveUser(userLike);
        } else {
            friendService.addContacts(Long.valueOf(userId), toUserId);
            huanXinTemplate.addContacts("HX" + userId, "HX" + toUserId);

            friendService.addContacts(toUserId, Long.valueOf(userId));
            // 3.环信添加好友
            huanXinTemplate.addContacts("HX" + toUserId, "HX" + Long.valueOf(userId));
        }



        //根据用户id删除推荐用户中信息
        recommendUserService.remove(toUserId);


    }

    //判断对方时候喜欢我
    public ResponseEntity alreadyLove(Long jiarenId) {
        //获取当前用户id
        Long toUserId = UserHolder.get().getId();
        UserLike userLike = recommendUserService.alreadyLove(toUserId, jiarenId);
        //判断如果有数据那就是对方喜欢我，如果没有数据那就是对方不喜欢我
        if (userLike == null) {
            return   ResponseEntity.ok(false);

        }
        return ResponseEntity.ok(true);
    }

    //互相喜
    public ResponseEntity findFanLoveLike() {
        //获取线程内的userId
        Long userId = UserHolder.get().getId();
        //调用rpc获取互相喜欢数量
        Long eachLoveCount = recommendUserService.findEachLoveCount(userId);
        //调用rpc获取我喜欢数量
        Long fanCount = recommendUserService.findFanCount(userId);
        //调用rpc获取喜欢我数量
        Long loveCount = recommendUserService.findLoveCount(userId);
        //创建userLikeCountVo表
        UserLikeCountVo vo = new UserLikeCountVo();
        vo.setEachLoveCount(eachLoveCount);
        vo.setFanCount(fanCount);
        vo.setLoveCount(loveCount);

        return ResponseEntity.ok(vo);
    }

    //根据类型查询所需要的分页数据（查询我喜欢的，我的粉丝，相互喜欢以及看我的人）
    public ResponseEntity findFriendsType(String type, Integer pageNum, Integer pageSize) {

        //获取线程内的userId
        Long userId = UserHolder.get().getId();
        //调用rpc查询
        PageBeanVo pageBeanVo = recommendUserService.findFriendsType(type, userId, pageNum, pageSize);

        //封装UserLikeVo
        List<UserLikeVo> voList = new ArrayList<>();
        List<UserLike> userLikeList = (List<UserLike>) pageBeanVo.getItems();
        List<Friend> friendList = (List<Friend>) pageBeanVo.getItems();
        List<Visitor> visitorList = (List<Visitor>) pageBeanVo.getItems();
        Boolean isLove;
        //遍历，判空
        if (type.equals("1")) {

            if (CollectionUtil.isNotEmpty(friendList)) {

                for (Friend friend : friendList) {
                    if (friend.getUserId() != userId) {
                        continue;
                    }
                    UserLikeVo vo = new UserLikeVo();
                    //查询用户信息
                    UserInfo userInfo = userInfoService.findByUserId(friend.getFriendId());
                    //根据friend查询对方id并查询双方匹配度
                    Long jiarenId = friend.getFriendId();
                    //查询与对方的匹配度
                    vo.setId(friend.getFriendId());//对方的id
                    vo.setAge(userInfo.getAge());//年龄
                    vo.setAvatar(userInfo.getAvatar());//头像
                    vo.setCity(userInfo.getCity());//地址
                    vo.setNickname(userInfo.getNickname());//昵称
                    vo.setGender(userInfo.getGender());//性别
                    vo.setEducation(userInfo.getEducation());
                    vo.setMarriage(userInfo.getMarriage());
                    vo.setAlreadyLove(true);
                    voList.add(vo);
                }
            }
        } else if (type.equals("4")) {
            if (CollectionUtil.isNotEmpty(visitorList)) {
                for (Visitor visitor : visitorList) {
                    UserLikeVo vo = new UserLikeVo();
                    //查询用户信息
                    UserInfo userInfo = userInfoService.findByUserId(visitor.getVisitorUserId());

                    vo.setId(visitor.getUserId());

                    vo.setAge(userInfo.getAge());//年龄

                    vo.setAvatar(userInfo.getAvatar());//头像

                    vo.setCity(userInfo.getCity());//地址

                    vo.setNickname(userInfo.getNickname());//昵称

                    vo.setGender(userInfo.getGender());//性别

                    vo.setEducation(userInfo.getEducation());

                    vo.setMarriage(userInfo.getMarriage());

                    vo.setMatchRate(visitor.getScore().intValue());
                    voList.add(vo);
                }
            }
        } else if (type.equals("2")){
            if (CollectionUtil.isNotEmpty(userLikeList)) {

                for (UserLike userLike : userLikeList) {
                    UserLikeVo vo = new UserLikeVo();
                    //查询用户信息
                    UserInfo userInfo = userInfoService.findByUserId(userLike.getLikeUserId());

                    RecommendUser recommendUser;
                    //获取佳人id并判断我是否喜欢对方
                    vo.setId(userLike.getLikeUserId());
                    vo.setAge(userInfo.getAge());//年龄
                    vo.setAvatar(userInfo.getAvatar());//头像
                    vo.setCity(userInfo.getCity());//地址
                    vo.setNickname(userInfo.getNickname());//昵称
                    vo.setGender(userInfo.getGender());//性别
                    vo.setEducation(userInfo.getEducation());
                    vo.setMarriage(userInfo.getMarriage());
                    userLike = recommendUserService.alreadyLove(userLike.getUserId(),userLike.getLikeUserId());
                    //判断如果查询到信息，我喜欢对方，如果没有查询到信息，我不喜欢
                    if (userLike == null) {
                        isLove = false;
                    } else {
                        isLove = true;
                    }
                    vo.setAlreadyLove(isLove);

                    voList.add(vo);
                }
            }
        } else if (type.equals("3")) {
            if (CollectionUtil.isNotEmpty(userLikeList)) {

                for (UserLike userLike : userLikeList) {
                    UserLikeVo vo = new UserLikeVo();
                    //查询用户信息
                    UserInfo userInfo = userInfoService.findByUserId(userLike.getUserId());

                    RecommendUser recommendUser;

                    //获取佳人id并判断对方是否喜欢我
                    vo.setId(userLike.getUserId());
                    vo.setAge(userInfo.getAge());//年龄
                    vo.setAvatar(userInfo.getAvatar());//头像
                    vo.setCity(userInfo.getCity());//地址
                    vo.setNickname(userInfo.getNickname());//昵称
                    vo.setGender(userInfo.getGender());//性别
                    vo.setEducation(userInfo.getEducation());
                    vo.setMarriage(userInfo.getMarriage());

                    userLike = recommendUserService.alreadyLove(userLike.getUserId(), userLike.getLikeUserId());

                    //判断如果查询到信息，我喜欢对方，如果没有查询到信息，我不喜欢
                    if (userLike == null) {
                        isLove = false;
                    } else {
                        isLove = true;
                    }
                    vo.setAlreadyLove(isLove);

                    voList.add(vo);
                }
            }
        }
        //将结果返回到pageBeanVo
        pageBeanVo.setItems(voList);

        return ResponseEntity.ok(pageBeanVo);
    }

    //粉丝喜欢
    public void fanSave(Long likeUserId) {
        //获取线程内的userId
        Long userId = UserHolder.get().getId();
        //封装userLike对象
        UserLike userLike = new UserLike();
        userLike.setLikeUserId(likeUserId);
        userLike.setUserId(userId);
        userLike.setCreated(System.currentTimeMillis());

        //调用rpc保存
        friendService.fanLove(userLike);
        //添加好友
        friendService.addContacts(userId, likeUserId);
        //环信添加好友
        huanXinTemplate.addContacts("HX" + userId, "HX" + likeUserId);
    }

    //粉丝不喜欢
    public void fanDelete(Long likeUserId) {
        //获取线程内的userId
        Long userId = UserHolder.get().getId();

        //判断双方是否是好友，如果是好友再将双方的好友关系清除
        UserLike userLike = recommendUserService.alreadyLove(likeUserId, userId);
        if (userLike != null) {
            friendService.deleteContacts(userId, likeUserId);
            huanXinTemplate.deleteContacts("HX" + userId, "HX" + likeUserId);
        }
        //调用rpc方法进行删除信息
        friendService.fanDisLove(userId, likeUserId);
        //清楚自己喜欢用户的标记

    }
}
